<?php

namespace App\Http\Controllers\Api;

use App\AboutUs;
use App\Coupons;
use App\DistributionTeam;
use App\Http\Services\CommonManager;
use App\Http\Services\DomainManager;
use App\Http\Services\FileManager;
use App\Http\Services\UserManager;
use App\User;
use App\UserAddress;
use App\UserCoupon;
use App\UserDrug;
use App\UserInfo;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Predis\Profile\RedisVersion240;

class UCenterController extends Controller
{
    /**
     * 获取用户信息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getUserInfo(Request $request){
        $enterpriseId=DomainManager::getEnterpriseId($request);
        if (!$enterpriseId)
            return response()->json(['level'=>'error','message'=>'域名未授权','data'=>[]]);

        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'success','message' => '请先登录！','data' => []]);

        $userBasicInfo = CommonManager::getUserBasicInfo($user->id);

        $user->user_info = $userBasicInfo;

        //分销统计人头数量
        $distributionTeamsCount = DistributionTeam::whereUserId($user->id)->count();

        $user->teams_count = $distributionTeamsCount;

        $user->zhigou=0;
        $user->huiyuan=1;
        $user->bond=2;
        $user->member_name='普通会员1';

        return response()->json(['level' => 'success','message' => '获取成功','data' => $user]);
    }

    /**
     * 获取我的优惠券
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getUserCoupon(Request $request){
        $enterpriseId=DomainManager::getEnterpriseId($request);
        if (!$enterpriseId)
            return response()->json(['level'=>'error','message'=>'域名未授权','data'=>[]]);

        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'success','message' => '请先登录!','data' => []]);

        $type  = $request->input('type')  ?? '';
        $limit = $request->input('limit') ?? 10;
        $page  = $request->input('page')  ?? 1;

        $pageInfo = [
            'limit' => $limit,
            'page'  => $page,
            'type'  => $type
        ];
        $page=$page-1;
        $userCoupon = UserCoupon::whereUserId($user->id);
        if($type == 'unused'){
            $userCoupon=$userCoupon->whereIsUse(0)
                ->whereIsLocking(0)
                ->where('end_time','>', date('Y-m-d H:i:s',time()));
        }else if($type == 'used'){
            $userCoupon = $userCoupon->whereIsUse(1);
        }else if($type == 'expired'){
            $userCoupon = $userCoupon->where('end_time','<=', date('Y-m-d H:i:s',time()));
        }

        $pageInfo['total'] = $userCoupon->count();

        $userCoupon = $userCoupon->orderBy('created_at','desc')
            ->offset($limit * $page)
            ->limit($limit)
            ->get();

        return response()->json(['level' => 'success','message' => '获取成功','data' => $userCoupon,'page_info' => $pageInfo]);
    }

    /**
     * 获取关于我们
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getAboutUs(Request $request){
        $enterpriseId=DomainManager::getEnterpriseId($request);
        if (!$enterpriseId)
            return response()->json(['level'=>'error','message'=>'域名未授权','data'=>[]]);

        $aboutUs = AboutUs::whereType('about_us')
            ->whereEnterpriseId($enterpriseId)
            ->first();

        return response()->json(['level' => 'success','message' => '获取成功','data' => $aboutUs]);
    }

    /**
     * 新增收货地址
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function newShippingAddress(Request $request){
        $enterpriseId=DomainManager::getEnterpriseId($request);
        if (!$enterpriseId)
            return response()->json(['level'=>'error','message'=>'域名未授权','data'=>[]]);

        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录!','data' => 'no_login']);

        /* if(is_null($user->phone) || $user->phone == '')
           return response()->json(['level' => 'error','message' => '请绑定手机号','data' => 'no_binding']); */

        $consignee = $request->input('consignee');
        $phone     = $request->input('phone');
        $province  = $request->input('province');
        $city      = $request->input('city');
        $area      = $request->input('area');
        $address   = $request->input('address');
//        $postcode  = $request->input('postcode');
        $isDefault = $request->input('is_default') ?? 0;
        $id        = $request->input('id') ?? 0;
        $lat        = $request->input('lat') ?? 0;
        $lng        = $request->input('lng') ?? 0;

        if(is_null($consignee) || $consignee == '')
            return response()->json(['level' => 'error','message' => '请输入收件人姓名']);

        if(is_null($phone) || $phone == '' || !preg_match("/^(1[3456789])[0-9]{9}$/", $phone))
            return response()->json(['level' => 'error','message' => '请正确输入收件人手机号码']);

        if(is_null($province) || $province == '')
            return response()->json(['level' => 'error','message' => '请选择所在省份']);

        if(is_null($city) || $city == '')
            return response()->json(['level' => 'error','message' => '请选择所在城市']);

        if(is_null($area) || $area == '')
            return response()->json(['level' => 'error','message' => '请选择所在地区']);

        if(is_null($address) || $address == '')
            return response()->json(['level' => 'error','message' => '请输入详细地址']);

//        if(is_null($postcode) || $postcode == '' || !preg_match("/^[0-9]{6}$/", $postcode))
//            return response()->json(['level' => 'error','message' => '请正确输入邮政编码']);


        $isUserAddress = UserAddress::whereUserId($user->id)->whereIsDefault(1)->first();
        if($isDefault == 1 && $isUserAddress){
            $isUserAddress->is_default = 0;
            $isUserAddress->save();
        }

        $newUserAddress = UserAddress::whereId($id)->first();
        if(!$newUserAddress){
            /** @var UserAddress $selectUserAdd */
            $selectUserAddress = UserAddress::whereUserId($user->id)->whereConsignee($consignee)->wherePhone($phone)->whereProvince($province)->whereCity($city)->whereArea($area)->whereAddress($address)->first();
            if($selectUserAddress)
                return response()->json(['level' => 'error','message' => '收货地址已存在']);


            $newUserAddress = new UserAddress();
        }

        $newUserAddress->user_id    = $user->id;
        $newUserAddress->consignee  = $consignee;
        $newUserAddress->phone      = $phone;
        $newUserAddress->province   = $province;
        $newUserAddress->city       = $city;
        $newUserAddress->area       = $area;
        $newUserAddress->address    = $address;
//        $newUserAddress->postcode   = $postcode;
        if ($lat)
            $newUserAddress->lat    = $lat;
        if ($lng)
            $newUserAddress->lng    = $lng;
        $newUserAddress->is_default = $isDefault;
        $newUserAddress->save();

        return response()->json(['level' => 'success','message' => '设置收货地址成功','data' => $newUserAddress]);
    }

    /**
     * 获取收货地址
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getShippingAddress(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录!','data' => 'no_login']);

        /* if(is_null($user->phone) || $user->phone == '')
           return response()->json(['level' => 'error','message' => '请绑定手机号','data' => 'no_binding']); */
        $limit = $request->input('limit') ?? 10;
        $page  = $request->input('page')  ?? 1;
        $id = $request->input('id') ?? 0;
        $page_info=[
            'page'=>$page,
            'limit'=>$limit,
            'total'=>UserAddress::whereUserId($user->id)->count()
        ];
        $page=$page-1;
        if($id != '' && $id != 0){
            $userAddress = UserAddress::whereUserId($user->id)
                ->whereId($id)->first();
            $page_info['limit']=1;
            $page_info['page']=1;
        }else{
            $userAddress = UserAddress::whereUserId($user->id)
                ->offset($page *$limit)
                ->limit($limit)
                ->get();
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $userAddress,'page_info'=>$page_info]);
    }

    /**
     * 删除收货地址
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     */
    public function deleteShippingAddress(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录!','data' => 'no_login']);

        /* if(is_null($user->phone) || $user->phone == '')
           return response()->json(['level' => 'error','message' => '请绑定手机号','data' => 'no_binding']); */

        $id = $request->get('id') ?? 0;

        $userAddress = UserAddress::whereUserId($user->id)
            ->whereId($id)
            ->first();
        if(!$userAddress)
            return response()->json(['level' => 'error','message' => '该收货地址不存在']);

        if($userAddress->is_default == 1){
            /** @var UserAddress $newestUserAddress */
            $newestUserAddress = UserAddress::whereUserId($user->id)
                ->orderBy('id','desc')
                ->first();
            if($newestUserAddress){
                $newestUserAddress->is_default = 1;
                $newestUserAddress->save();
            }
        }
        $userAddress->delete();
        return response()->json(['level' => 'success','message' => '删除成功']);
    }

    /**
     * 获取用药人列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getUserDrugList(Request $request){
        $enterpriseId=DomainManager::getEnterpriseId($request);
        if (!$enterpriseId)
            return response()->json(['level'=>'error','message'=>'域名未授权','data'=>[]]);

        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录!','data' => 'no_login']);

        $limit     = $request->input('limit') ?? 20;
        $page      = $request->input('page') ?? 1;
        $isDefault = $request->input('is_default') ?? '';

        $pageInfo = [
            'limit' => $limit,
            'page' => $page
        ];

        $page -= 1;

        $userDrugList = UserDrug::whereUserId($user->id)
            ->whereEnterpriseId($enterpriseId);

        if(is_numeric($isDefault)){
            $userDrugList = $userDrugList->whereIsDefault($isDefault);
        }

        $pageInfo['total'] = $userDrugList->count();

        $userDrugList = $userDrugList->orderByDesc('id')->offset($limit * $page)->limit($limit)->get();

        return response()->json(['level' => 'success','message' => '获取成功','data' => $userDrugList,'page_info' => $pageInfo]);
    }

    /**
     * 获取用药人详情
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getUserDrugDetail(Request $request){
        $enterpriseId=DomainManager::getEnterpriseId($request);
        if (!$enterpriseId)
            return response()->json(['level'=>'error','message'=>'域名未授权','data'=>[]]);

        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录!','data' => 'no_login']);

        $id = $request->input('id') ?? 0;

        $userDrug = UserDrug::getUserDrugInfo($id);

        return response()->json(['level' => 'success','message' => '获取成功','data' => $userDrug]);
    }

    /**
     * 设置用药人
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function setUserDrug(Request $request){
        $enterpriseId=DomainManager::getEnterpriseId($request);
        if (!$enterpriseId)
            return response()->json(['level'=>'error','message'=>'域名未授权','data'=>[]]);

        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录!','data' => 'no_login']);

        $patientName     = $request->input('patientName') ?? '';
        $patientSex      = $request->input('patientSex') ?? 0;
        $patientAge      = $request->input('patientAge') ?? 0;
        $patientWeight   = $request->input('patientWeight') ?? 0;
        $patientPhone    = $request->input('patientPhone') ?? '';
        $patientIdcard   = $request->input('patientIdcard') ?? '';
        $patientBirthday = $request->input('patientBirthday') ?? '';
        $relationship    = $request->input('relationship') ?? 0;
        $patientAddress  = $request->input('patientAddress') ?? '';
        $pmh             = $request->input('pmh') ?? '';
        $amh             = $request->input('amh') ?? '';
        $fmh             = $request->input('fmh') ?? '';
        $nurse           = $request->input('nurse') ?? '';
        $liver           = $request->input('liver') ?? '';
        $renal           = $request->input('renal') ?? '';
        $isDefault       = $request->input('is_default') ?? 0;
        $id              = $request->input('id') ?? 0;

        if(empty($patientName))
            return response()->json(['level' => 'error','message' => '请填写姓名！']);

        if(empty($patientSex))
            return response()->json(['level' => 'error','message' => '请选择性别！']);

        if(empty($patientAge))
            return response()->json(['level' => 'error','message' => '请填写年龄！']);

        if(empty($patientWeight))
            return response()->json(['level' => 'error','message' => '请填写体重！']);

        if(empty($patientBirthday))
            return response()->json(['level' => 'error','message' => '请填写出生日期！']);

        if(empty($patientAddress))
            return response()->json(['level' => 'error','message' => '请填写用药人地址！']);

        if(empty($patientPhone))
            return response()->json(['level' => 'error','message' => '请填写手机号！']);

        $phoneVerification = CommonManager::phoneVerification($patientPhone);
        if(!$phoneVerification)
            return response()->json(['level' => 'error','message' => '请正确输入手机号码！']);

        if(empty($patientIdcard))
            return response()->json(['level' => 'error','message' => '请填写身份证号！']);

        $idCardVerification = CommonManager::idCardVerification($patientIdcard);
        if(!$idCardVerification)
            return response()->json(['level' => 'error','message' => '请正确输入身份证号！']);

        $isUserDrug = UserDrug::whereUserId($user->id)->whereEnterpriseId($enterpriseId)->whereIsDefault(1)->first();
        if($isDefault == 1 && $isUserDrug){
            $isUserDrug->is_default = 0;
            $isUserDrug->save();
        }

        $newUserDrug = UserDrug::whereId($id)->first();
        if(!$newUserDrug)
            $newUserDrug = new UserDrug();

        $newUserDrug->user_id           = $user->id;
        $newUserDrug->enterprise_id     = $enterpriseId;
        $newUserDrug->patientName       = $patientName;
        $newUserDrug->patientSex        = $patientSex;
        $newUserDrug->patientAge        = $patientAge;
        $newUserDrug->patientWeight     = $patientWeight;
        $newUserDrug->patientPhone      = $patientPhone;
        $newUserDrug->patientIdcard     = $patientIdcard;
        if($patientBirthday)
             $newUserDrug->patientBirthday   = $patientBirthday;
        $newUserDrug->relationship      = $relationship;
        $newUserDrug->patientAddress    = $patientAddress;
        $newUserDrug->pmh               = $pmh;
        $newUserDrug->amh               = $amh;
        $newUserDrug->fmh               = $fmh;
        $newUserDrug->nurse             = $nurse;
        $newUserDrug->liver             = $liver;
        $newUserDrug->renal             = $renal;
        $newUserDrug->is_default        = $isDefault;
        $newUserDrug->save();

        $isUserDrug = UserDrug::whereUserId($user->id)->whereEnterpriseId($enterpriseId)->whereIsDefault(1)->first();
        if(!$isUserDrug){
            $isUserDrug = UserDrug::whereUserId($user->id)->whereEnterpriseId($enterpriseId)->first();
            if($isUserDrug){
                $isUserDrug->is_default = 1;
                $isUserDrug->save();
            }
        }

        return response()->json(['level' => 'success','message' => '设置成功','data' => $newUserDrug]);
    }

    /**
     * 删除用药人
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     */
    public function delUserDrug(Request $request){
        $enterpriseId=DomainManager::getEnterpriseId($request);
        if (!$enterpriseId)
            return response()->json(['level'=>'error','message'=>'域名未授权','data'=>[]]);

        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录!','data' => 'no_login']);

        $id = $request->input('id') ?? 0;

        $userDrug = UserDrug::whereId($id)->first();
        if(!$userDrug)
            return response()->json(['level' => 'error','message' => '用药人数据不存在']);

        if($userDrug->is_default == 1){
            $isUserDrug = UserDrug::whereUserId($user->id)->whereEnterpriseId($enterpriseId)->first();
            if($isUserDrug){
                $isUserDrug->is_default = 1;
                $isUserDrug->save();
            }
        }

        $userDrug->delete();

        return response()->json(['level' => 'success','message' => '删除成功','data' => $userDrug]);
    }
}
